let main = document.querySelector("#main")
let backbtn = document.querySelector(".back")
let home = document.querySelector(".home")
let info = document.querySelector("#info")
let sendbtn = document.querySelector("#send")
let ullist = document.querySelector("#main ul")

console.log(main)
console.log(backbtn)
console.log(home)
console.log(info)
console.log(send)

//main.scrollTop=main.scrollHeight

let cookieMsg = document.cookie
console.log(cookieMsg)
if (/user/.test(cookieMsg)) {
    let userobj={}
    let cookieArr=cookieMsg.split("; ")
    console.log(cookieArr)
    for(let key of cookieArr){
        console.log(key)
        console.log(key.indexOf("user"))
        if(key.indexOf("user")!= -1){
            userobj=JSON.parse(key.split("=")[1])
        }
    }
    console.log(userobj)

    let ws = new WebSocket("ws://192.168.43.250:9999")
    // console.log(JSON.stringify({"self":"meduo"}))
    ws.onopen = function () {
        ws.send(JSON.stringify({ "self": userobj.user }))
    }
    ws.onmessage = function (msg) {

        if (msg.data === "您以上线") {
            let msgHtml = ullist.innerHTML + `
        <li>
            <div class="other">
                <h3>${"System"}</h3>
                <p>${msg.data}</p>
            </div>
        </li>
        `
            ullist.innerHTML = msgHtml
            main.scrollTop = main.scrollHeight
        } else {
            msg = JSON.parse(msg.data)
            let msgHtml = ullist.innerHTML + `
        <li>
            <div class="other">
                <h3>${msg.sendID}</h3>
                <p>${msg.value}</p>
            </div>
        </li>
        `
            ullist.innerHTML = msgHtml
            main.scrollTop = main.scrollHeight
        }

    }

    sendbtn.addEventListener("click", () => {
        let value = info.value;
        ws.send(JSON.stringify({ "id": "0", "value": value }))
        info.value = ""
        let msgHtml = ullist.innerHTML + `
    <li>
        <div class="self">
            <h3>${userobj.user}</h3>
            <p>${value}</p>
        </div>
    </li>
    `
        ullist.innerHTML = msgHtml
        main.scrollTop = main.scrollHeight
    })
} else {
    console.log("您未登录")
}


